package com.imooc.tx;

import com.imooc.mq.InitResumeMQProducerHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.DefaultTransactionStatus;

import javax.sql.DataSource;

/**
 * 自定义事务管理器
 * @author liansen
 * @create 03-18-16:10
 */
@Component
public class MyTransactionManager extends DataSourceTransactionManager {

    @Autowired
    private InitResumeMQProducerHandler producerHandler;

    public MyTransactionManager(@Qualifier("dataSource") DataSource dataSource) {
        super(dataSource);
    }

    @Override
    protected void doCommit(DefaultTransactionStatus status) {
        try{
            super.doCommit(status);
        }finally {
            //事务提交以后，发送ThreadLocal中的消息(这些消息都是当前线程下未发送的)
            producerHandler.sendAllLocalMsg();
        }
    }
}
